<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Created by PhpStorm.
 * User: liuweiping
 * Date: 16/7/16
 * Time: 16:52
 */
class Api extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library(array('session'));
        $this->load->helper(array('url', 'host', 'api', 'user', 'download', 'date'));
    }

    /**
     * 默认首页, 提示信息
     */
    public function index()
    {
        $this->load->view('api');
    }

    /**
     * 一般接口和文件上传接口.
     * @return bool 是否请求成功
     */
    public function gateway()
    {
        try {
            $method = $this->input->method(TRUE);
            if ($method == 'POST') {
                $params = $_POST;
            } else {
                $params = $_GET;
            }
            log_message('error', 'GATEWAY [' . $method . "] PARAMS-> " . json_encode($params));

            ob_start('ob_gzhandler');
            // 判断是否登录
//            if (!isLogin()) {
//                echo getError(ERROR_NO_LOGIN, '请先登录您的账号');
//                return false;
//            }
            // 已登录
            if (empty($params)) {
                echo getError(ERROR_NO_PARAMS, '参数为空');
                return false;
            }
            $service = $params['service'];
            if (empty($service)) {
                echo getError(ERROR_PARAMS, 'service参数错误');
                return false;
            }
            // 参数去掉 service
            $params = array_diff_key($params, array('service' => ''));
            $files = $_FILES;
            $header = $this->input->request_headers();
            $result = api_request($service, $params, $header, $files);
            log_message('error', 'GATEWAY [' . $method . '] <' . $service . "> RESULT-> " . $result);

            // result 为 false 或 空，说明无请求结果
            if (!$result)
                echo getError(ERROR_NO_RESPONSE, '请求服务器失败');
            else if (empty($result))
                echo getError(ERROR_EMPTY_RESPONSE, '服务器返回为空');
            else {
                $accept = $header['Accept'];
                if (strstr($accept, 'application/json')) {
                    header('Content-type:application/json; charset=UTF-8');
                } else if (strstr($accept, 'text/html')) {
                    header('Content-type:text/html; charset=UTF-8');
                }

                header('Access-Control-Allow-Origin:*');
                echo $result;
            }
            return true;
        } catch (Exception $e) {
            log_message("error", $e->getMessage());
            echo getError(ERROR_NO_RESPONSE, '请求服务器失败' . $e->getMessage());
        }
        return false;
    }


    /**
     * 下载文件接口，AJAX请求不可用
     * @return bool
     */
    public function download()
    {
        if ($this->input->is_ajax_request()) {
            echo getError(ERROR_NONSUPPORT_AJAX, "不支持 ajax 请求");
            return false;
        }
        try {
            $method = $this->input->method(TRUE);
            if ($method == 'POST')
                $params = $_POST;
            else
                $params = $_GET;

            log_message('error', 'DOWNLOAD [' . $method . "] PARAMS-> " . json_encode($params));
            // 判断是否登录
            if (!isLogin()) {
                $this->load->view('download', array('msg' => '请先登录您的账号'));
                return false;
            }
            // 已登录

            $service = $params['service'];
            if (empty($service)) {
                $this->load->view('download', array('msg' => 'service参数错误'));
                return false;
            }

            // 参数去掉 service
            $params = array_diff_key($params, array('service' => ''));
            $params = fixCommonParams($params);

            // 流式下载到客户端
            $header = $this->input->request_headers();
            url_download($service, $params, $header);

            return true;
        } catch (Exception $e) {
            log_message("error", $e->getMessage());
            $this->load->view('download', array('msg' => '请求服务器失败', 'error' => $e->getMessage()));
        }
        return false;
    }

    /**
     * CK 编辑器使用的上传图片接口 (专用)
     * @return bool
     */
    public function uploadImage()
    {
        // 判断是否登录
        if (!isLogin()) {
            echo '请先登录您的账号';
            echo '<br>';
            echo '<a class="btn btn-primary" href="/">重试</a>';
            return false;
        }
        // 已登录

        if ($this->input->method(TRUE) == 'POST') {
            $params = $_POST;
        } else {
            $params = $_GET;
        }
        $params = fixCommonParams($params);
        try {
            $url = API_HOST . '/plover/web/notice/save_img';
            // 添加文件上传
            if ($_FILES == null) {
                echo '没有发现图片文件';
                echo '<br>';
                echo '<a class="btn btn-primary" href="javascript:window.history.back()">重试</a>';
                return false;
            }
            foreach ($_FILES as $key => $file) {
                $file_path = $file['tmp_name'];
                $file_type = $file['type'];
                $file_name = $file['name'];

                $fileObj = new CURLFile(realpath($file_path), $file_type, $file_name);
                $params['notice_img'] = $fileObj;
                break;
            }
            $result = postData($url, $params);
            if (empty($result)) {
                echo '服务器没有反应';
                echo '<br>';
                echo '<a class="btn btn-primary" href="javascript:window.history.back()">重试</a>';
                return false;
            }
            $json = json_decode($result, true);
            $code = $json['code'];
            switch ($code) {
                case 0:
                    $body = $json['body'];
                    if (!empty($body)) {
                        $imgUrl = $body['url'];
                        $callback = $_REQUEST["CKEditorFuncNum"];
                        echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($callback,'" . $imgUrl . "','');</script>";
                    }
                    break;
                default:
                    echo $json['msg'];
                    echo '<br>';
                    echo '<a class="btn btn-primary" href="javascript:window.history.back()">重试</a>';
                    return false;
            }
        } catch (Exception $e) {
            log_message("error", $e->getMessage());
            echo '服务器出错: ' . $e->getMessage();
            echo '<br>';
            echo '<a class="btn btn-primary" href="javascript:window.history.back()">重试</a>';
        }
        return true;
    }

    /**
     * 获取百度统计的ID
     */
    public function getBaiduId()
    {
        $id = $_SERVER['BAIDU_TONGJI_ID'];
        log_message('error', 'getBaiduId = ' . $id);
        echo json_encode(array(
            'code' => SUCCESS,
            'msg' => $id,
            'from' => 'PHP'
        ));
    }
}